本篇同步發布於Blog:[解題] LeetCode - 217 Contains Duplicate
LeetCode
217 - Contains Duplicate
https://leetcode.com/problems/contains-duplicate/
輸入1個陣列nums,求nums元素是否有重複。
比如範例輸入的nums = [1,2,3,1],元素1重複,所以要回傳true。
使用HashSet,每次檢查是否該元素已在HashSet裡,有的話就回傳true,否則把它加進HashSet。
難度為Easy
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> repeat;
for(int i = 0; i < nums.size();++i){
if(repeat.count(nums[i])){
return true;
}
repeat.insert(nums[i]);
}
return false;
}
};
int main() {
vector<int> nums{1,2,3,1};
Solution sol;
cout << sol.containsDuplicate(nums) << endl;
return 0;
}
using System;
using System.Collections.Generic;
namespace LeetCode217
{
public class Solution {
public bool ContainsDuplicate(int[] nums) {
HashSet<int> repeat = new HashSet<int>();
for(int i = 0; i < nums.Length;++i){
if(repeat.Contains(nums[i])){
return true;
}
repeat.Add(nums[i]);
}
return false;
}
}
class Program
{
static void Main(string[] args)
{
int[] nums = new int[]{1,2,3,1};
Solution sol = new Solution();
Console.WriteLine(sol.ContainsDuplicate(nums));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/200-299/217.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/200-299/217.cs